<template>
  <live-pusher :beauty="beauty" v-if="type == 1" class="live" id="livePusherContext" :url="data.liveInfo.push_url"
    mode="HD" auto-focus></live-pusher>
  <live-player v-else class="live" id="livePlayer" :src="data.liveInfo.pull_url" autoplay
    @statechange="statechange"></live-player>
  <view class="u-flex-y-center u-p-l-20 u-p-r-20 u-flex-between" :style="{'padding-top':navHeight+'px'}">
    <view class="u-flex-y-center nav-item">
      <u-image width="48rpx" height="48rpx" :src="prefixURL(data.liveInfo.cover_img)" shape="circle"
        :fade="false"></u-image>
      <u-text :text="data.liveInfo.title" color="#fff" size="13" margin="0 0 0 10rpx"></u-text>
    </view>
    <view class="u-flex-y-center">
      <view class="u-flex-y-center nav-item">
        <image class="nav-num" src="/static/images/01_37rc.png" :fade="false"></image>
        <u-text :text="data.total_num" color="#fff" size="13" margin="0 0 0 10rpx"></u-text>
      </view>
      <u-image src="/static/images/01_37bug.png" @click="handleBack" width="52rpx" height="52rpx"
        customStyle="marginLeft:26rpx"></u-image>
    </view>
  </view>
  <view @click="handleLikes" class="comment-box u-flex-items-end u-flex">
    <scroll-view scroll-y :scroll-top="scrollTop" scroll-with-animation>
      <block v-for="(item,index) in messageList" :key="index">
        <view class="comment-item u-flex-y-center">
          <view class="comment-name" v-if="item.cloudCustomData != 'notice'">{{item.nick}}</view>
          <text>{{item.payload.text}}</text>
        </view>
      </block>
    </scroll-view>
  </view>
  <view class="action-bar">
    <view class="u-flex-y-center u-flex-between">
      <view>
        <houseItem :item="data.liveInfo.house_lst[0]" v-if="data.liveInfo.house_lst.length"></houseItem>
      </view>
      <view class="action-right">
        <view class="u-m-b-36">
          <u-image width="52rpx" customStyle="margin:auto" height="52rpx"
            src="/static/images/01_31dainzan.png"></u-image>
          <u-text :text="data.likes" align="center" color="#fff" size="13"></u-text>
        </view>
        <button open-type="share" class="share-btn">
          <u-image src="/static/images/01_37kguf.png" width="76rpx" height="76rpx"></u-image>
        </button>
      </view>
    </view>
    <view class="u-flex-y-center u-m-t-20">
      <view class="live-input u-p-20 u-flex-1 u-flex-y-center">
        <u-image customStyle="marginRight: 20rpx" src="/static/images/01_37qsr.png" width="28rpx"
          height="28rpx"></u-image>
        <u-input color="#fff" border="none" v-model="keyword" @confirm="_sendMessage" placeholder="请输入内容"
          class="u-m-l-16"></u-input>
      </view>
      <u-image @click="handleGift" src="/static/images/01_37ih.png" width="76rpx" height="76rpx"
        customStyle="margin: 0 20rpx"></u-image>
      <u-image @click="handleCart" src="/static/images/01_37igut.png" width="76rpx" height="76rpx"></u-image>
    </view>
  </view>
  <up-popup :show="data.cartShow" :round="16" @close="handleCart">
    <view class="u-p-24">
      <block v-for="(item,index) in data.liveInfo.coupon_lst" :key="item.id">
        <coupon-item :item="item" type='3'></coupon-item>
      </block>
      <u-empty v-if="!data.liveInfo.coupon_lst.length"></u-empty>
    </view>
  </up-popup>
  <up-popup :show="data.show" :round="16" @close="handleGift">
    <view class="gift-title">赠送礼物</view>
    <swiper indicator-dots :duration="1000" style="height: 450rpx;" :current="data.current" @change="swiperChange">
      <swiper-item>
        <view class="u-p-l-24 u-p-r-24">
          <u-row :gutter="10">
            <u-col span="3" v-for="item in data.giftList" :key="item.id">
              <view :class="['gift-item', gift_id==item.id?'active':'']" @click="changeGift(item)">
                <image :src="prefixURL(item.image)" mode=""></image>
                <view>{{item.name}}</view>
              </view>
            </u-col>
          </u-row>
        </view>
      </swiper-item>
    </swiper>
    <view class="u-flex-y-center u-m-t-24 u-p-l-24 u-p-r-24">
      <up-button plain color="#F87610" shape="circle" @click="data.show = false">关闭</up-button>
      <up-button color="#F87610" shape="circle" customStyle="marginLeft:24rpx" @click="_give_gift">赠送</up-button>
    </view>
  </up-popup>

  <image src="@/static/images/icon_love.png" v-if="isDoubleTap" :style="{left:likesX +'px',top:likesY +'px'}"
    class="heart-animation" mode=""></image>

</template>

<script setup>
  import houseItem from '@/components/house-item/house-item.vue';
  import couponItem from '../components/coupon-item.vue';
  import TencentCloudChat from '@tencentcloud/chat'
  import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
  import { Livedetail, close_live, getLikes, gift_lst, give_gift, liveLikes } from '../../../config/api';
  import { getCache, prefixURL, setCache } from '../../../util/util';
  import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
  import { throttle } from 'uview-plus'
  const props = defineProps({
    id: {
      type: String,
      default: ''
    },
    type: {
      type: [Number, String],
      default: 1
    },
		user_id:{
			type:[Number,String],
			default:''
		}
  })
  const beauty = computed(() => {
    return uni.getSystemInfoAsync().osName == 'ios' ? 1 : 5
  })
	if(props.user_id){
		setCache('invite',props.user_id)
	}
  onShareTimeline(() => {
    let userInfo = getCache('userInfo')
    return {
      path: `pages/index/houseLive/livePusher?id=${props.id}&type=2&user_id=${userInfo.user_id}`
    }
  })
  onShareAppMessage(() => {
    let userInfo = getCache('userInfo')
    return {
      path: `pages/index/houseLive/livePusher?id=${props.id}&type=2&user_id=${userInfo.user_id}`
    }
  })
  const scrollTop = computed(() => messageList.value.length * 999)
  const keyword = ref('')
  const navHeight = computed(() => uni.getSystemInfoSync().statusBarHeight + 40)
  const data = ref({
    show: false,
    cartShow: false,
    likes: 0,
    liveInfo: {
      house_lst: [],
      coupon_lst: []
    },
    current: 0,
    giftList: [],
    userInfo: getCache('userInfo'),
    total_num: 0, //在线人数
  })
  const gift_id = ref('')
  const messageList = ref([])
  const playerCtx = ref('')
  const livePusherContext = ref("")
  const timer = ref('')
  const detailTimer = ref('')

  /**********/
  const tapCount = ref(0)
  const tapTimer = ref('')
  const isDoubleTap = ref(false)
  const likesX = ref('')
  const likesY = ref('')
  /*********/
  onMounted(() => {
    _Livedetail()
    _gift_lst()
    _onMessage()
    detailTimer.value = setInterval(() => {
      _getLikes()
    }, 5000)
  })
  onBeforeUnmount(() => {
    clearInterval(timer.value)
    clearInterval(detailTimer.value)
  })
  const statechange = (e) => {
    if (e.detail.code == 3) {
      uni.$u.toast('直播已结束')
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    }
  }
  // 双击点赞
  const handleLikes = (e) => {
    if (isDoubleTap.value) return
    likesX.value = e.detail.x - 25
    likesY.value = e.detail.y - 25
    tapCount.value++;
    if (tapCount.value === 1) {
      // 第一次点击，设置计时器  
      tapTimer.value = setTimeout(() => {
        tapCount.value = 0; // 重置点击次数  
        isDoubleTap.value = false; // 重置双击状态  
      }, 200); // 设定双击的时间间隔，比如200毫秒  
    } else if (tapCount.value === 2) {
      // 如果在短时间内发生了第二次点击，则认为是双击  
      liveLikes({ id: props.id }).then(res => {
        clearTimeout(tapTimer.value); // 清除计时器  
        isDoubleTap.value = true; // 设置双击状态为true  
        tapCount.value = 0; // 重置点击次数  
        setTimeout(() => {
          isDoubleTap.value = false
        }, 800)
      })
    }
  }
  // 获取点赞数和直播状态
  const _getLikes = () => {
    getLikes({ id: props.id }).then(res => {
      console.log(res)
      data.value.likes = res.data.likes
      if (res.data.status != 1) {
        uni.$u.toast(res.msg)
        uni.navigateBack()
      }
    })
  }
  // 赠送礼物
  const _give_gift = () => {
    if (!gift_id.value) {
      uni.$u.toast('请选择赠送的礼物')
      return
    }
    give_gift({ room_id: props.id, gift_id: gift_id.value }).then(res => {
      let text = data.value.giftList.find(item => item.id == gift_id.value).name
      let message = uni.$chat.createTextMessage({
        to: data.value.liveInfo.group_id,
        conversationType: TencentCloudChat.TYPES.CONV_GROUP,
        payload: {
          text: `${data.value.userInfo.nickname}赠送了${text} x1`
        },
        cloudCustomData: 'notice'
      })
      uni.$chat.sendMessage(message).then((res) => {
        console.log(res)
        gift_id.value = ''
        data.value.show = false
        messageList.value.push(res.data.message)
      })
    })

  }
  // 选择礼物
  const changeGift = (row) => {
    gift_id.value = gift_id.value == row.id ? '' : row.id
  }
  const _onMessage = () => {
    uni.$chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, data => {
      console.log(data)
      data.data = data.data.filter(item => item.nick && item.payload.text)
      if (messageList.value[0]?.cloudCustomData != 'notice') {
        messageList.value.unshift({
          cloudCustomData: 'notice',
          payload: {
            text: `欢迎来到直播间!直播提倡
          绿色直播，严谨涉政涉恐、
          涉黄、聚众闹事返现等内
          容网警24小时巡查。请勿
          参与直播间非官方奖励活
          动、游戏，切勿私下交易
          以防受骗`
          }
        })
      }

      messageList.value = messageList.value.concat(data.data)
    })
  }
  const _sendMessage = () => {
    let message = uni.$chat.createTextMessage({
      to: data.value.liveInfo.group_id,
      conversationType: TencentCloudChat.TYPES.CONV_GROUP,
      payload: {
        text: keyword.value
      },
    })
    uni.$chat.sendMessage(message).then(res => {
      keyword.value = ''
      messageList.value.push(res.data.message)
    })
  }
  // 发送消息
  const swiperChange = (e) => {
    data.value.current = e.detail.current
    _gift_lst()
  }
  // 礼物列表
  const _gift_lst = () => {
    gift_lst({ page: data.value.current + 1, limit: 8 }).then(res => {
      data.value.giftList = res.data
      console.log(data.value.giftList)
    })
  }
  // 直播详情
  const _Livedetail = () => {
    Livedetail({ id: props.id ,user_id:props.user_id}).then(res => {
      data.value.liveInfo = res.data
      data.value.likes = res.data.likes
      uni.$chat.joinGroup({ groupID: data.value.liveInfo.group_id, type: 'AVChatRoom' })
      if (props.type == 1) {
        livePusherContext.value = uni.createLivePusherContext('livePusherContext')
        livePusherContext.value.start()
      } else {
        playerCtx.value = uni.createLivePlayerContext("livePlayer")
        playerCtx.value.play()
      }
      timer.value = setInterval(() => {
        uni.$chat.getGroupOnlineMemberCount(data.value.liveInfo.group_id).then(res => {
          console.log(res)
          data.value.total_num = res.data.memberCount
        })
      }, 6000)
    })
  }
  const handleBack = () => {
    if (props.type == 1) {
      uni.showModal({
        content: '确定关闭直播吗',
        success: ({ confirm }) => {
          if (confirm) {
            close_live({ id: props.id,total_people:data.value.total_num }).then(res => {
              uni.$u.toast(res.msg)
              uni.navigateBack()
            })
          }
        }
      })
    } else {
      uni.navigateBack()
    }
  }
  const handleGift = () => {
    data.value.show = !data.value.show
  }
  const handleCart = () => {
    data.value.cartShow = !data.value.cartShow
  }
</script>

<style scoped lang="scss">
  .live {
    width: 100%;
    height: 100vh;
    position: absolute;
    z-index: 0;
  }

  .nav-item {
    padding: 6rpx 20rpx 6rpx 10rpx;
    background: rgba(0, 0, 0, .3);
    border-radius: 40rpx;
    position: relative;

    .nav-num {
      width: 30rpx;
      height: 26rpx;
    }
  }

  .comment-box {
    position: fixed;
    bottom: 400rpx;
    left: 20rpx;
    height: 950rpx;
    z-index: 1;
    right: 20rpx;

    scroll-view {
      position: relative;
      z-index: 0;
      height: 600rpx;
    }

    .comment-item {
      max-width: 500rpx;
      padding: 10rpx 20rpx;
      background: rgba(0, 0, 0, .3);
      border-radius: 30rpx;
      color: #fff;
      font-size: 26rpx;
      font-weight: 500;
      margin-top: 20rpx;
      width: fit-content;

      .comment-name {
        color: #FFE7D4;
        font-size: 26rpx;
        font-weight: 800;
        margin-right: 10rpx;
      }
    }
  }

  .action-bar {
    padding: 20rpx;
    bottom: env(safe-area-inset-bottom);
    position: fixed;
    left: 0;
    right: 0;

    .live-input {
      border-radius: 44rpx;
      background: rgba(0, 0, 0, .3);
      color: #fff;
      font-size: 26rpx;
    }
  }

  .gift-title {
    font-size: 28rpx;
    color: #000;
    font-weight: 800;
    text-align: center;
    padding: 24rpx 0;
  }

  .gift-item {
    height: 186rpx;
    background: linear-gradient(180deg, #FBFBFB 0%, #EEEEEE 100%);
    border-radius: 20rpx;
    text-align: center;
    color: #000;
    padding: 12rpx;
    font-weight: 500;
    margin-bottom: 20rpx;
    font-size: 24rpx;

    image {
      width: 90rpx;
      height: 90rpx;
      margin-bottom: 26rpx;
    }

  }

  .active {
    border: 1px solid #f86d4e;
  }

  ::v-deep .u-row {
    flex-wrap: wrap;
  }



  .heart-animation {
    width: 100rpx;
    /* 根据你的小心心图片大小调整 */
    height: 100rpx;
    /* 根据你的小心心图片大小调整 */
    animation: heartBounce 1s ease-in-out forwards;
    /* 添加动画效果 */
    position: fixed;
  }

  @keyframes heartBounce {
    0% {
      transform: scale(1);
      opacity: 1;
    }

    50% {
      transform: scale(1.2);
      opacity: 0.8;
    }

    100% {
      transform: scale(1);
      opacity: 1;
    }
  }
</style>